package com.zeus.base.smscenter.restful.api.controller;

import com.alibaba.fastjson.JSON;

import com.smscenter.server.core.QueryStrategy;
import com.smscenter.server.core.ems.EmsQuery;
import com.smscenter.server.core.vcomcn.VComQuery;
import com.smscenter.server.core.welink.WelinkQuery;
import com.smscenter.server.core.ztsms.ZtSmsQuery;
import com.wordnik.swagger.annotations.ApiOperation;

import com.zeus.base.smscenter.restful.api.model.ResultModel;
import com.zeus.base.smscenter.model.SmsSupplierProperty;
import com.zeus.base.smscenter.model.Tenant;
import com.zeus.base.smscenter.restful.api.model.ResultStatus;
import com.zeus.base.smscenter.service.ISmsSettingService;
import com.zeus.base.smscenter.service.ISupplierPropertyService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 升级版查询接口
 * @author: hailong
 * @date： 2016年10月25日
 *
 */
@RestController
@RequestMapping("/smsqueryV2")
public class NewQueryController {
    Logger log = Logger.getLogger(this.getClass());
    
    @Autowired
    private ISupplierPropertyService smsSupplierPropertyService;
    
    @Autowired
    private ISmsSettingService tenantService;

    @RequestMapping(value = "/queryBalanceV2", method = RequestMethod.POST)
    @ApiOperation(value = "短信帐户余额查询")
    public ResponseEntity<ResultModel> queryBalance(@RequestParam(value = "tenant") String tenant, @RequestParam(value = "data") String data) {
    	Map resMap = initResMap();//初始化返回,默认都为0
		
    	Tenant qt = new Tenant();
    	qt.setCode(tenant);
    	Tenant rst = tenantService.findByCode(qt);//查询用户信息
    	
    	if (rst != null) {
        	Map<String, Object> params = new HashMap<String, Object>();
        	//处理短信查询
        	try {
        		//查询短信,查询的是租户的默认通道,一个文字一个语音
        		resMap = handleQueryBalance(resMap, rst, "sms", params);//查询文字
        		params.clear();
//				if (!rst.getDefaultSmsSupplierNo().equals("5"))//助通短信不需要查询语音
				resMap = handleQueryBalance(resMap, rst, "voice", params);//查询语音
            }catch (Exception e){
                log.error(e.getMessage());
                return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, e.getMessage()), HttpStatus.OK);
            }
		}else{
			return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "查无该租户"), HttpStatus.OK);
		}
        return new ResponseEntity(ResultModel.ok(resMap), HttpStatus.OK);
    }


	private Map initResMap() {
		Map resMap = new HashMap();//返回map
    	resMap.put("sms_balance", "0");//剩余多少条
		resMap.put("sms_money", "0");//余额
		resMap.put("sms_supplier", "0");//通道
		resMap.put("voice_balance", "0");
		resMap.put("voice_money", "0");
		resMap.put("voice_supplier", "0");
		return resMap;
	}

    
	private QueryStrategy getQueryStrategy(String supplierNo) {
		if(supplierNo.equals("1"))//即时通fytest1 82557339
			return new QueryStrategy(new VComQuery());
		else if(supplierNo.equals("2"))//易信通：fyrjgstc  fyrjgstcfy56
			return new QueryStrategy(new EmsQuery());
		else if(supplierNo.equals("3"))
			return new QueryStrategy(new WelinkQuery());
		else if(supplierNo.equals("5"))
			return new QueryStrategy(new ZtSmsQuery());
		return null;
	}
	
	
	/**
	 * 通用调查询接口,将返回的值分类型放至返回的map里
	 * @param resMap 反回map
	 * @param rst 租户
	 * @param type 类型二选一     sms为文字  voice为语音
	 * @param params 参数map
	 * @return
	 * @throws Exception
	 */
	private Map handleQueryBalance(Map resMap, Tenant rst, String type,Map<String, Object> params) throws Exception {
		String supplierNo = null;//通道
		if ("VOICE".equals(type.toUpperCase())) {//如果是语音,取语音的通道
			supplierNo = rst.getDefaultVoiceSupplierNo();
		} else {
			supplierNo = rst.getDefaultSmsSupplierNo();
		}
		params.put("code", rst.getCode());
		params.put("supplierNo", supplierNo);
		
		List<SmsSupplierProperty> smsSupplierPropertyList = smsSupplierPropertyService.find(params);
		if (smsSupplierPropertyList != null && smsSupplierPropertyList.size() > 0) {
			for (SmsSupplierProperty smsSupplierProperty : smsSupplierPropertyList) {
		        params.put(smsSupplierProperty.getPropertyName(), smsSupplierProperty.getPropertyValue());
		    }
			params.put("sendType", type.toUpperCase());
			QueryStrategy queryStrategy = getQueryStrategy(supplierNo);
			resMap.put(type.toLowerCase() + "_supplier", supplierNo);//通道
			String resJson = queryStrategy.queryBalanceV2(params);
			System.out.println("================"+resJson);
	    	Map rj = JSON.parseObject(resJson);
	    	resMap.put(type.toLowerCase() + "_balance", rj.get("balance"));//剩余多少条
			resMap.put(type.toLowerCase() + "_money", rj.get("money"));//余额
		}
		return resMap;
	}

}

